import CryptoJS from 'crypto-js'

export function AESKey() {
    // 生成随机的16位字符AES密钥
    let randomNum = ""    // 生成一个随机的字符串
    let arrays = new Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
    );
    for (let i = 0; i < 6; i++) {
        let r = parseInt(Math.random() * arrays.length);
        randomNum += arrays[r];
    }
    let salt = CryptoJS.lib.WordArray.random(128 / 8);
    let key128Bits = CryptoJS.PBKDF2(randomNum, salt, { keySize: 128 / 64 });
    const wordArray = CryptoJS.enc.Utf8.parse(key128Bits)
    const key_origin = CryptoJS.enc.Base64.stringify(wordArray);
    return key_origin;
}

//加密
export function encryptAES(params) {
    var key = CryptoJS.enc.Base64.parse(uni.getStorageSync('VMSKEY'));
    // var iv = key // 加密向量和加密key是一样的
    var jsonData = JSON.stringify(params);
    //下面的data参数要求是一个字符串，第一次用的时候我直接传递的是一个对象，出现了错误，要转换成字符串
    var data = CryptoJS.enc.Utf8.parse(jsonData);
    var encrypted = CryptoJS.AES.encrypt(
        data,
        key,
        { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString();
    return encrypted;
}
//解密
export function decryptAES(word) {
    var key = CryptoJS.enc.Base64.parse(uni.getStorageSync('VMSKEY'));
    // var iv = key
    var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return JSON.parse(decrypt.toString(CryptoJS.enc.Utf8))
}
